const express = require("express");
const puppeteer = require("puppeteer");
const ejs = require("ejs");
const { createCanvas, loadImage } = require("canvas");
const FormData = require("form-data");
const fs = require("fs");
const path = require("path");
const marked = require("marked");
const axios = require("axios");
const { config } = require("./config");

const app = express();
app.use(express.static(path.join(__dirname, "images")));
app.set("view engine", "ejs");
app.use(express.json());
const port = 3000;
let token = "";
// import { getUseUuid, strRandomHandle } from '@/utils'
const { convertImagesToBase64, saveImage } = require("./utils/index");

let imagePathList = [
  "bpai.png",
  "code.png",
  "consult.png",
  "foot-bg.png",
  "zx-answer.png",
  "zx-question.png",
];
let base64Obj = convertImagesToBase64(imagePathList);

// 假设这是获取消息的函数
async function getMessagesByIds(postData, authorization) {
  // 这里应该是从数据库或其他服务获取消息

  try {
    // console.log("token---", token);
    // 发起 GET 请求
    const response = await axios.post(
      `${config.server}/eims/BPai/wechat/getContentByShareId`,
      postData,
      {
        headers: {
          authorization,
          //   'Content-Type': 'application/json'
        },
      }
    );
    // console.log("response--", response);
    // 处理响应数据

    return response.data;
  } catch (error) {
    console.error("Error fetching data:", error);
    // res.status(500).send("Error fetching data");
    // res.status(500).json({
    //   success: false,
    //   message: "Error fetching data",
    //   error: error.message, // 你也可以返回更多的错误信息
    // });
  }
}

function processMessages(messages) {
  if (!messages || !messages.length) return [];

  return messages.map((item) => {
    let recordContent = item.recordContent
      ? JSON.parse(item.recordContent)
      : {};
    recordContent.contextMsg = recordContent.contextMsg.replace(/\\n/g, "\r\n");

    return {
      ...recordContent,
      ...item,
      status: "done",
      recommend: [],
      message: recordContent.contextMsg,
      type: recordContent.direction === "Q" ? "send" : "receive",
    };
  });
}

async function getCode(shareId, authorization) {
  try {
    let postData = {
      scene: `shareId=${shareId}`, // 替换为实际的 scene 参数
      page: "pages/chat/list", // 替换为实际的页面路径
      envVersion: config.env === "prod" ? "release" : "trial", // 体验版
      // checkPath: true, // 替换为实际的页面路径
    };
    const response = await axios.post(
      `${config.server}/portal/enterprise/taxes/user/getUnlimitedQRCode`,
      postData,
      {
        headers: {
          authorization,
          //   'Content-Type': 'application/json'
        },
      }
    );
    // console.log("response--", response);
    return response.data.result.code;
    // throw Error('二维码生成失败')
  } catch (err) {
    console.log("err", err);
    // res.status(500).json({
    //   success: false,
    //   message: "Error fetching data",
    //   error: err.message, // 你也可以返回更多的错误信息
    // });
  }
}

app.post("/generate-image", async (req, res) => {
  try {
    let totalHei = 0
    let isEnd =false
    const { shareId, mobile } = req.body;
    const { authorization } = req.headers;
    const { result } = await getMessagesByIds(
      {
        shareId,
      },
      authorization
    );
    const query = {
      mobile,
    };
    // 转换对话列表
    let list = processMessages(result.list);

    // 使用 marked 将 Markdown 转换为 HTML
    const htmlContent = marked.parse(list[0].message);
    console.log("htmlContent--", htmlContent);
    // 设置适合小程序封面的宽高
    const width = 300;
    const height = 400;
    const canvas = createCanvas(width, height);
    const ctx = canvas.getContext("2d");

    // 设置背景颜色
    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, width, height);

    // 加载本地头像图片并绘制到 canvas 的第一行
    try {
      let avator =
        list[0].type == "send"
          ? "images/zx-question.png"
          : "images/zx-answer.png";
      const avatarImage = await loadImage(path.join(__dirname, avator)); // 使用本地路径加载头像
      const avatarSize = 30; // 头像的大小为 50x50
      ctx.drawImage(avatarImage, 20, 20, avatarSize, avatarSize); // 将头像绘制在指定位置
    } catch (error) {
      console.error("Error loading avatar image:", error);
    }

    // 设置文本样式并处理 Markdown 样式（如标题和文本）
    ctx.fillStyle = "#ffffff";

    ctx.font = "20px";
    ctx.textAlign = "left";
    // ctx.fillText("分享封面", 50, y);
    // y += 10;

    // 将 Markdown 解析后的 HTML 内容处理为文本并绘制
    // const processHtml = (html) => {
    //   const lines = html.split("\n");
    //   lines.forEach((line) => {
    //     ctx.font = "16px Arial";
    //     console.log('line.replace(/<[^>]+>/g, "")--',line.replace(/<[^>]+>/g, ""));
    //     ctx.fillText(line.replace(/<[^>]+>/g, ""), 50, y);
    //     y += 30;
    //   });
    // };
    const processHtml = (html, ctx, startY, canvas) => {
      let lines = html.split("\n"); // 分割行
      let y = startY;
      console.log("lines", lines);
      // 手动处理每一行
      // lines.forEach((line) => {
      //   const cleanLine = line.replace(/<[^>]+>/g, "").trim(); // 去除 HTML 标签
      //   if (cleanLine) {
      //     wrapText(ctx, cleanLine, 20, y, 180, 20); // 处理长文本自动换行
      //     y += 20; // 行距
      //   }
      // });
      let lineHeight = 20;
      let currentY = startY;
      // lines.forEach((line) => {
      //   // 将 HTML 标签替换为空字符
      //   // const text = line.replace(/<[^>]+>/g, "").trim();
      //   const text = '这是一段特别长的文本这是一段特别长的文本这是一段特别长的文本这是一段特别长的文本这是一段特别长的文本这是一段特别长的文本这是一段特别长的文本'

      //   // 逐行绘制文本
      //   if (text) {
      //     const words = text.split(" ");
      //     let lineBuffer = "";

      //     words.forEach((word) => {
      //       const testLine = lineBuffer + word + " ";
      //       const metrics = ctx.measureText(testLine);
      //       console.log('metrics--',metrics);
      //       const testWidth = metrics.width;
      //       console.log('testWidth--',testWidth);

      //       // 检查是否超出 Canvas 边界
      //       if (testWidth > canvas.width - 20) {
      //         // 检查 y 是否超出 Canvas 高度
      //         if (currentY + lineHeight > canvas.height) {
      //           console.log("文本超出 Canvas 高度，停止绘制");
      //           return; // 如果超出高度，停止绘制
      //         }

      //         // 如果超出边界，绘制当前行并清空缓存
      //         ctx.fillText(lineBuffer, 20, currentY,canvas.width - 20);
      //         lineBuffer = word + " "; // 开始新行
      //         y += lineHeight; // 行高
      //       } else {
      //         lineBuffer = testLine; // 缓存当前行
      //       }
      //     });

      //     // 绘制最后一行
      //     if (currentY + lineHeight <= canvas.height) {
      //       ctx.fillText(lineBuffer, 20, y);
      //       currentY += lineHeight; // 行高
      //     }
      //   }
      // });
      lines = lines
        .map((line) => line.replace(/<[^>]+>/g, "").trim())
        .filter((item) => item);
      lines = getNewLine(lines, ctx, 260);
      console.log("lines----", lines);
      // lines.forEach(line => {
      //   // 将 HTML 标签替换为空字符
      //   const text = line.replace(/<[^>]+>/g, "").trim();

      //   // 逐行绘制文本
      //   // if (text) {
      //   //   y = drawText(ctx, line, 20, currentY, canvas.width - 20,20,canvas);
      //   // }
      //  if(text){
      //   // y = drawText(ctx, line, 20, y, canvas.width - 20,20,canvas);

      //   y = drawText(ctx, line, 20, y, canvas.width - 40);
      // }
      // });

      // let currentY = 20; // 从顶部20px开始绘制
      lines.forEach((line) => {
        y = wrapText(ctx, line, 20, y, canvas.width - 40, 20);
      });
    };

    processHtml(htmlContent, ctx, 70, canvas);

    // 将生成的图片保存为 PNG
    let buffer = canvas.toBuffer("image/png");

    if (!Buffer.isBuffer(buffer)) {
      buffer = Buffer.from(screenshotBuffer);
      // return;
    }

    const formData = new FormData();
    // 将 Buffer 添加到 FormData 中，作为文件上传

    // 将 Blob 添加到 FormData 对象，假设键名为 'image'
    formData.append("file", buffer, "image.jpeg");
    formData.append("fileType", "5");

    url = await uploadFile(formData);
    const imagePath = path.join(__dirname, "path/to/share-image.png");
    fs.writeFileSync(imagePath, buffer);

    console.log("imagePath--", imagePath);
    // saveImage(url);

    // 返回图片路径
    res.json({ code: "200", message: "操作成功", result: { url } });
  } catch (error) {
    console.error("Error fetching data:", error);
    res.status(500).json({
      success: false,
      message: "Error fetching data",
      error: error.message, // 你也可以返回更多的错误信息
    });
  }
});

function getNewLine(originalArray, ctx, maxPixelLength) {
  // 设置字体样式（根据实际使用的字体设置）
  ctx.font = "20px"; // 根据实际字体大小调整

  const newArray = [];

  // 遍历原始数组
  for (let item of originalArray) {
    // 计算当前文本的像素长度
    const textWidth = ctx.measureText(item).width;

    // 如果文本长度超过最大像素长度，进行切割
    if (textWidth > maxPixelLength) {
      let currentString = "";
      let remainingText = item;

      while (remainingText.length > 0) {
        const charToAdd = remainingText.charAt(0);
        const newString = currentString + charToAdd;
        const newTextWidth = ctx.measureText(newString).width;

        // 如果添加当前字符后不超过最大像素长度，继续添加
        if (newTextWidth <= maxPixelLength) {
          currentString = newString;
          remainingText = remainingText.slice(1); // 移除已添加的字符
        } else {
          // 添加到新数组并重置
          newArray.push(currentString);
          currentString = ""; // 重置当前字符串
        }
      }

      // 添加最后剩余的字符串（如果有的话）
      if (currentString.length > 0) {
        newArray.push(currentString);
      }
    } else {
      // 如果文本长度不超过最大像素长度，直接保留
      newArray.push(item);
    }
  }
  return newArray;
}

function drawText1(ctx, text, x, y, maxWidth, lineHeight, canvas) {
  const words = text.split(" ");
  let lineBuffer = "";

  words.forEach((word) => {
    const testLine = lineBuffer + word + " ";
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;

    // 检查是否超出 Canvas 边界
    if (testWidth > maxWidth) {
      // 检查 y 是否超出 Canvas 高度
      if (y + lineHeight > canvas.height) {
        console.log("文本超出 Canvas 高度，停止绘制");
        return; // 如果超出高度，停止绘制
      }

      // 绘制当前行并清空缓存
      ctx.fillText(lineBuffer, x, y);
      lineBuffer = word + " "; // 开始新行
      y += lineHeight; // 行高
    } else {
      lineBuffer = testLine; // 缓存当前行
    }
  });

  // 绘制最后一行
  if (lineBuffer && y + lineHeight <= canvas.height) {
    ctx.fillText(lineBuffer, x, y);
  }

  return y; // 返回当前的 y 坐标
}

function drawText33(ctx, text, x, y, maxWidth, lineHeight, canvas) {
  // 去除 HTML 标签
  text = text.replace(/<[^>]+>/g, "");
  let currentY = y;
  let words = text.split(" ");
  let lineBuffer = "";
  // console.log('words---',words);
  // words = words.filter(item => item.length > 0)
  words.forEach((word) => {
    const testLine = lineBuffer + word + " ";
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;
    console.log("metrics", metrics);
    // 检查是否超出 Canvas 边界
    if (testWidth > maxWidth) {
      // 检查 y 是否超出 Canvas 高度
      if (currentY + lineHeight > canvas.height) {
        console.log("文本超出 Canvas 高度，停止绘制");
        return; // 如果超出高度，停止绘制
      }

      // 绘制当前行并清空缓存
      ctx.fillText(lineBuffer, x, currentY);
      lineBuffer = word + " "; // 开始新行
      console.log("lineBuffer1---", lineBuffer);
      currentY += 40; // 行高
      console.log("currentY---", currentY);
    } else {
      lineBuffer = testLine; // 缓存当前行
    }
  });

  // 绘制最后一行
  if (lineBuffer && currentY + lineHeight <= canvas.height) {
    console.log("最后一行", lineBuffer);
    ctx.fillText(lineBuffer, x, currentY);
  }

  return currentY; // 返回当前的 y 坐标
}

function wrapText(context, text, x, y, maxWidth, lineHeight) {
  let words = text.split(" ");
  let line = "";

  for (let n = 0; n < words.length; n++) {
    let testLine = line + words[n] + " ";
    let metrics = context.measureText(testLine);
    let testWidth = metrics.width;
    if (testWidth > maxWidth && line.length > 0) {
      context.fillText(line, x, y);
      line = words[n] + " ";
      y += lineHeight;
    } else {
      line = testLine;
    }
  }
  context.fillText(line, x, y);
  y += lineHeight; // 移动到下一行
  return y; // 返回新的y位置
}

// let currentY = 20; // 从顶部20px开始绘制
// lines.forEach((line) => {
//   currentY = wrapText(ctx, line, 10, currentY, canvasWidth, 20);
// });

function drawText(ctx, text, x, y, maxWidth) {
  const words = text.split(" ");
  let line = "";

  words.forEach((word) => {
    const testLine = line + word + " ";
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;

    if (testWidth > maxWidth) {
      if (line) {
        ctx.fillText(line, x, y, maxWidth);
        y += 24; // 行高
      }
      line = word + " "; // 开始新行
    } else {
      line = testLine; // 添加到当前行
    }
  });

  if (line) {
    ctx.fillText(line, x, y, maxWidth); // 绘制最后一行
  }

  return y; // 返回当前y坐标，以便于继续绘制后续内容
}

const uploadFile = (formData) => {
  return new Promise((resolve, reject) => {
    axios
      .post(`${config.server}/tenant/manager/package/uploadFile`, formData, {
        headers: {
          // authorization,
          "Content-Type": "multipart/form-data",
          "Client-Type": "mobile",
        },
      })
      .then((res) => {
        // console.log("res--", res.data.result);
        resolve(res.data.result);
      })
      .catch((err) => {
        console.log("err----", err);
        reject(err);
      });
  });
};

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
